package com.kcsj.controller.basic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kcsj.domain.MarkDown;
import com.kcsj.service.MarkDownService;
import com.kcsj.util.JSONUtil;
import com.kcsj.util.MessageHelper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author 胡庆阳
 * 29th Nov. 2020
 */
@Slf4j
@WebServlet("/markDown")
public class MarkDownController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //根据request对象，获得代表参数的JSON字串
        String json = JSONUtil.getJSON(request);
        try {
            MarkDown markDown = JSON.parseObject(json, MarkDown.class);
            MarkDownService.getInstance().add(markDown);
            JSONObject message = MessageHelper.addMessage("添加成功");
            response.getWriter().println(message);
        }catch (SQLException e){
            JSONObject message = MessageHelper.dateBaseError();
            e.printStackTrace();
            //响应message到前端
            response.getWriter().println(message);
        }catch(Exception e){
            JSONObject message = MessageHelper.netWordError();
            e.printStackTrace();
            //响应message到前端
            response.getWriter().println(message);
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Integer userId = Integer.parseInt(request.getAttribute("userId").toString());
        try {
            //查找备忘录内容
            MarkDown markDown = MarkDownService.getInstance().find(userId);
            String json = JSON.toJSONString(markDown);
            JSONObject data = MessageHelper.addData(json);
            //响应department_json到前端
            response.getWriter().println(data);
        }catch (SQLException e){
            log.error(e.getMessage());
            JSONObject message = MessageHelper.dateBaseError();
            response.getWriter().println(message);;
        }catch(Exception e){
            JSONObject message = MessageHelper.netWordError();
            e.printStackTrace();
            //响应message到前端
            response.getWriter().println(message);
        }
    }
}
